/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EditSkolemFunctionBox.java
 *
 * Created on 11/10/2009, 04:57:50
 */
package gui;

import base.KnowledgeBaseManager;
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import exceptions.UnDecidibleValueException;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import logicaDePredicados.PredicateConstant;
import logicaDePredicados.SkolemFunction;

/**
 *
 * @author Francisco Gindre
 */
public class EditSkolemFunctionBox extends javax.swing.JFrame {

    File baseFile;
    List<String> elementList= null;
    SkolemFunction<String, String> targetSkolem;
    ObjectContainer db;

    public EditSkolemFunctionBox(SkolemFunction<String, String> toEdit, File selectedFile) {
        baseFile = selectedFile;
          WindowListener windowListener = new WindowAdapter() {
            // anonymous WindowAdapter class

            @Override
            public void windowClosing(WindowEvent w) {
                // Whatever application code you want to do on close, e.g.
                if (db != null) {
                    
                    db.rollback();
                    db.close();
                    w.getWindow().dispose();
                } else {
                    ErrorFrame error = new ErrorFrame("Database Error: Could not store object");
                    error.setVisible(true);

                }

                // Whatever code you want to actually close the JFrame, e.g.

            } // end windowClosing
        };// end anonymous class
        this.addWindowListener(windowListener);

    

        try {
            db = Db4oEmbedded.openFile(KnowledgeBaseManager.getConfiguration(), baseFile.getAbsolutePath());
            ObjectSet<SkolemFunction<String, String>> resultSet = db.queryByExample(toEdit);
            if (resultSet.size() > 1) {
                new ErrorFrame("Duplicate Predicate on knowledge Base");
                setVisible(true);
                this.processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));

            } else {
                targetSkolem = resultSet.next();
             
            }

        } catch (Exception e) {
            e.printStackTrace();


            this.processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));

        }




        setTitle("Edit: " + targetSkolem.getName());
        initComponents();
        SkolemFunctionNameTextField.setText(toEdit.getName());
        returnValueTextField.setText((String) keyComboBox.getSelectedItem());

        refresh();
    }

    /** Creates new form EditSkolemFunctionBox */
    public EditSkolemFunctionBox() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        keyComboBox = new javax.swing.JComboBox(new javax.swing.DefaultComboBoxModel(targetSkolem.getKeyList().toArray(new String [0])));
        jLabel4 = new javax.swing.JLabel();
        returnValueTextField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        updateButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        newReturnValueTextField = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        newValueTextField = new javax.swing.JTextField();
        addValueButton = new javax.swing.JButton();
        SkolemFunctionNameTextField = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        removeButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);

        jLabel2.setText("Return Value");
        jLabel2.setName("jLabel2"); // NOI18N

        saveButton.setText("Save");
        saveButton.setName("saveButton"); // NOI18N
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.setName("cancelButton"); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        keyComboBox.setModel(new javax.swing.DefaultComboBoxModel(targetSkolem.getKeyList().toArray(new String [0])));
        keyComboBox.setName("keyComboBox"); // NOI18N
        keyComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                keyComboBoxActionPerformed(evt);
            }
        });

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/resources/icons/background.png"))); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        returnValueTextField.setName("returnValueTextField"); // NOI18N
        returnValueTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                returnValueTextFieldActionPerformed(evt);
            }
        });

        jLabel1.setText("Key");
        jLabel1.setName("jLabel1"); // NOI18N

        updateButton.setText("Update value");
        updateButton.setName("updateButton"); // NOI18N
        updateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateButtonActionPerformed(evt);
            }
        });

        jLabel3.setText("New Value");
        jLabel3.setName("jLabel3"); // NOI18N

        newReturnValueTextField.setName("newReturnValueTextField"); // NOI18N
        newReturnValueTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newReturnValueTextFieldActionPerformed(evt);
            }
        });

        jLabel5.setText("New Return Value");
        jLabel5.setName("jLabel5"); // NOI18N

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel6.setText("Base File:");
        jLabel6.setName("jLabel6"); // NOI18N

        jLabel7.setText(baseFile.getAbsolutePath());
        jLabel7.setName("jLabel7"); // NOI18N

        newValueTextField.setName("newValueTextField"); // NOI18N

        addValueButton.setText("Add new value");
        addValueButton.setName("addValueButton"); // NOI18N
        addValueButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addValueButtonActionPerformed(evt);
            }
        });

        SkolemFunctionNameTextField.setName("SkolemFunctionNameTextField"); // NOI18N

        jLabel8.setText("Skolem Function Name");
        jLabel8.setName("jLabel8"); // NOI18N

        removeButton.setText("remove");
        removeButton.setName("removeButton"); // NOI18N
        removeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(44, 44, 44)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addComponent(jLabel4)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(318, 318, 318)
                        .addComponent(saveButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel7))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(SkolemFunctionNameTextField, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(keyComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, 107, Short.MAX_VALUE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(newValueTextField, javax.swing.GroupLayout.Alignment.LEADING))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel5)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(returnValueTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(newReturnValueTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(35, 35, 35)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(addValueButton)
                                    .addComponent(updateButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(removeButton)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jLabel7))
                .addGap(18, 18, 18)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(SkolemFunctionNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(keyComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(returnValueTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(removeButton)
                    .addComponent(updateButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newReturnValueTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(newValueTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(addValueButton))
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(saveButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void returnValueTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_returnValueTextFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_returnValueTextFieldActionPerformed

    private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateButtonActionPerformed
        String value = returnValueTextField.getText();
        if (value!=null && !value.equalsIgnoreCase("")){

        targetSkolem.addValue((String) keyComboBox.getSelectedItem(), returnValueTextField.getText());
        }else {
            new ErrorFrame ("return value field is empty").setVisible(true);
        }
        refresh();
    }//GEN-LAST:event_updateButtonActionPerformed

    private void newReturnValueTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newReturnValueTextFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_newReturnValueTextFieldActionPerformed

    private void keyComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_keyComboBoxActionPerformed
        try {
        returnValueTextField.setText(targetSkolem.calculate((String)keyComboBox.getSelectedItem()).getValue());

        }catch (UnDecidibleValueException e){
            new ErrorFrame("Error: could not edit value").setVisible(true);
        }
    }//GEN-LAST:event_keyComboBoxActionPerformed

    private void addValueButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addValueButtonActionPerformed

        if (newValueTextField.getText().equals("")  || newReturnValueTextField.getText().equals("")||
                newValueTextField.getText() == null || newReturnValueTextField.getText() == null) {
            ErrorFrame error = new ErrorFrame("Error: missing input field value");
            error.setVisible(true);

        } else {
            targetSkolem.addValue(newValueTextField.getText(), newReturnValueTextField.getText());
            newValueTextField.setText(null);
            newReturnValueTextField.setText(null);
            refresh();
        }


    }//GEN-LAST:event_addValueButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        this.processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed

        targetSkolem.setName(SkolemFunctionNameTextField.getText());
        if (db != null) {
            db.store(targetSkolem);
            db.commit();
            db.close();
            this.dispose();
        } else {
            new ErrorFrame("Database Error").setVisible(true);

        }
       

    }//GEN-LAST:event_saveButtonActionPerformed

    private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed
        
        targetSkolem.removeKey((String) keyComboBox.getSelectedItem());
        refresh();
    }//GEN-LAST:event_removeButtonActionPerformed

    private void refresh() {

        elementList = null;
        returnValueTextField.setText(null);
        elementList= targetSkolem.getKeyList();
        keyComboBox.setModel(new DefaultComboBoxModel(elementList.toArray()));
        

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new EditSkolemFunctionBox().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField SkolemFunctionNameTextField;
    private javax.swing.JButton addValueButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JComboBox keyComboBox;
    private javax.swing.JTextField newReturnValueTextField;
    private javax.swing.JTextField newValueTextField;
    private javax.swing.JButton removeButton;
    private javax.swing.JTextField returnValueTextField;
    private javax.swing.JButton saveButton;
    private javax.swing.JButton updateButton;
    // End of variables declaration//GEN-END:variables
}
